//
//  ContentView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import SwiftUI

struct ContentView: View {
    @StateObject private var dataManager = DataManager.shared
    @StateObject private var performanceMonitor = LaunchPerformanceMonitor.shared
    @State private var showingLogin = false
    @State private var isDataLoaded = false
    @State private var hasStartedTimeout = false
    
    var body: some View {
        Group {
            if !isDataLoaded {
                LaunchScreenView()
            } else if dataManager.currentUser != nil || dataManager.isGuestMode {
                MainTabView()
                    .environmentObject(dataManager)
            } else {
                LoginView()
                    .environmentObject(dataManager)
            }
        }
        .onAppear {
            // 开始性能监控
            performanceMonitor.startMonitoring()
            
            // 初始化音频会话配置，确保视频播放不受干扰
            AudioSessionManager.shared.configureForVideoPlayback()
            
            // 标记数据加载开始
            performanceMonitor.markDataLoadingStart()
            
            // 开始数据加载检查
            checkDataLoadingStatus()
            
            // 启动超时保护机制 - 优化启动速度
            if !hasStartedTimeout {
                hasStartedTimeout = true
                DispatchQueue.main.asyncAfter(deadline: .now() + LaunchConfig.dataLoadingTimeout) {
                    if !isDataLoaded {
                        withAnimation(.easeInOut(duration: LaunchConfig.splashFadeOutDuration)) {
                            isDataLoaded = true
                        }
                        
                        // 如果没有用户登录，自动进入访客模式
                        if dataManager.currentUser == nil && !dataManager.isGuestMode {
                            dataManager.loginAsGuest()
                        }
                    }
                }
            }
        }
        .onReceive(dataManager.$menuItems) { _ in
            checkDataLoadingStatus()
        }
        .onReceive(dataManager.$availableCoupons) { _ in
            checkDataLoadingStatus()
        }
    }
    
    private func checkDataLoadingStatus() {
        // 检查关键数据是否已加载完成
        if !dataManager.menuItems.isEmpty && !dataManager.availableCoupons.isEmpty {
            // 标记数据加载完成
            performanceMonitor.markDataLoadingEnd()
            
            // 快速启动：最小化过渡延时
            let delay = LaunchConfig.enableFastLaunch ? LaunchConfig.dataLoadingTransitionDelay : 0.3
            DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
                withAnimation(.easeInOut(duration: LaunchConfig.splashFadeOutDuration)) {
                    isDataLoaded = true
                }
                
                // 标记启动完成
                performanceMonitor.markLaunchComplete()
                
                // 延迟执行非关键操作，避免阻塞启动
                if LaunchConfig.enableLazyLoading {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        self.performNonCriticalInitialization()
                    }
                } else {
                    performNonCriticalInitialization()
                }
                
                // 首次打开应用时自动进入访客模式，显示主页面
                if dataManager.currentUser == nil && !dataManager.isGuestMode {
                    dataManager.loginAsGuest()
                }
            }
        }
    }
    
    /// 执行非关键初始化操作
    private func performNonCriticalInitialization() {
        // 清除所有测试账户的预存信息，用于真机测试
        dataManager.clearAllTestData()
    }
}

struct MainTabView: View {
    @EnvironmentObject var dataManager: DataManager
    @State private var selectedTab = AppConfig.Navigation.defaultTabAfterLogin
    @State private var selectedOrderSegment = 0
    
    var body: some View {
        TabView(selection: $selectedTab) {
            HomeView(selectedTab: $selectedTab)
                .tabItem {
                    Image(systemName: "house.fill")
                    Text(dataManager.currentLanguage == "zh" ? "首页" : "Home")
                }
                .tag(0)
            
            MenuView()
                .tabItem {
                    Image(systemName: "menucard.fill")
                    Text(dataManager.currentLanguage == "zh" ? "菜单" : "Menu")
                }
                .tag(1)
            
            CartView()
                .tabItem {
                    Image(systemName: "cart.fill")
                    Text(dataManager.currentLanguage == "zh" ? "购物车" : "Cart")
                }
                .badge(dataManager.cartItemCount > 0 ? dataManager.cartItemCount : 0)
                .tag(2)
            
            OrderStatusView(selectedSegment: $selectedOrderSegment)
                .tabItem {
                    Image(systemName: "list.clipboard.fill")
                    Text(dataManager.currentLanguage == "zh" ? "订单" : "Orders")
                }
                .badge(dataManager.activeOrderCount > 0 ? dataManager.activeOrderCount : 0)
                .tag(3)
            
            NavigationView {
                MeView()
                    .environmentObject(dataManager)
                    .navigationTitle(dataManager.currentLanguage == "zh" ? "会员中心" : "Member Center")
                    .navigationBarTitleDisplayMode(.inline)
                    .navigationBarBackButtonHidden(true)
            }
            .navigationViewStyle(StackNavigationViewStyle())
            .tabItem {
                Image(systemName: "person.circle.fill")
                Text(dataManager.currentLanguage == "zh" ? "我的" : "Me")
            }
            .tag(4)
        }
        .tabViewStyle(.automatic)
        .accentColor(
            Color(red: 1.0, green: 0.5, blue: 0.0) // 用户指定的橙色
        )
        .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("NavigateToCart"))) { _ in
            selectedTab = AppConfig.Navigation.tabAfterVoucherPurchase
        }
        .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("NavigateToMenu"))) { _ in
            selectedTab = AppConfig.Navigation.tabAfterCouponUse
        }
        .onChange(of: dataManager.shouldNavigateToOrdersCurrent) { shouldNavigate in
            if shouldNavigate {
                selectedTab = 3 // Orders tab
                selectedOrderSegment = 0 // Current segment
                dataManager.shouldNavigateToOrdersCurrent = false
            }
        }
        .onChange(of: dataManager.shouldNavigateToOrdersHistory) { shouldNavigate in
            if shouldNavigate {
                selectedTab = 3 // Orders tab
                selectedOrderSegment = 1 // History segment
                dataManager.shouldNavigateToOrdersHistory = false
            }
        }
        .alert(isPresented: $dataManager.showingCouponUnlockAlert) {
            Alert(
                title: Text(dataManager.currentLanguage == "zh" ? "购买成功" : "Purchase Successful"),
                message: Text(dataManager.couponUnlockAlertMessage),
                dismissButton: .default(Text("OK")) {
                    // 点击 OK 后跳转到 All Coupons 页面（Me Tab）
                    selectedTab = 4
                    dataManager.shouldNavigateToAllCoupons = true
                }
            )
        }
        .onAppear {
            // 自定义TabBar外观
            let appearance = UITabBarAppearance()
            appearance.configureWithTransparentBackground()
            appearance.backgroundEffect = UIBlurEffect(style: .systemUltraThinMaterialDark)
            
            // 设置选中状态的颜色
            appearance.stackedLayoutAppearance.selected.iconColor = UIColor(red: 1.0, green: 0.5, blue: 0.0, alpha: 1.0)
            appearance.stackedLayoutAppearance.selected.titleTextAttributes = [
                .foregroundColor: UIColor(red: 1.0, green: 0.5, blue: 0.0, alpha: 1.0),
                .font: UIFont.systemFont(ofSize: 10, weight: .semibold)
            ]
            
            // 设置未选中状态的颜色
            appearance.stackedLayoutAppearance.normal.iconColor = UIColor(red: 0.6, green: 0.6, blue: 0.7, alpha: 0.8)
            appearance.stackedLayoutAppearance.normal.titleTextAttributes = [
                .foregroundColor: UIColor(red: 0.6, green: 0.6, blue: 0.7, alpha: 0.8),
                .font: UIFont.systemFont(ofSize: 10, weight: .medium)
            ]
            
            // 添加顶部分割线
            appearance.shadowColor = UIColor(red: 1.0, green: 0.5, blue: 0.0, alpha: 0.3)
            appearance.shadowImage = UIImage()
            
            UITabBar.appearance().standardAppearance = appearance
            UITabBar.appearance().scrollEdgeAppearance = appearance
            
            // 创建8色渐变背景图像
            let _ = createGradientImage()
            
            // 移除全局导航栏设置，让每个视图自己管理导航栏外观
            
            // 移除表格视图背景设置
            // UITableView.appearance().backgroundColor = UIColor(patternImage: gradientImage)
            // UITableViewCell.appearance().backgroundColor = UIColor.clear
            // UITableViewCell.appearance().selectionStyle = .none
            
            // 移除全局背景设置，以允许每个视图管理自己的背景
            // UIView.appearance(whenContainedInInstancesOf: [UITabBarController.self]).backgroundColor = UIColor(patternImage: gradientImage)
        
        }
    }
    
    // 创建8色渐变背景图像的辅助函数
    private func createGradientImage() -> UIImage {
        let size = CGSize(width: 100, height: 100)
        let renderer = UIGraphicsImageRenderer(size: size)
        
        return renderer.image { context in
            let cgContext = context.cgContext
            
            // 定义8色渐变颜色
            let colors = [
                UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0).cgColor,      // 纯黑色
                UIColor(red: 0.05, green: 0.02, blue: 0.08, alpha: 1.0).cgColor,   // 深紫黑
                UIColor(red: 0.08, green: 0.04, blue: 0.12, alpha: 1.0).cgColor,   // 紫黑色
                UIColor(red: 0.12, green: 0.06, blue: 0.15, alpha: 1.0).cgColor,   // 深紫灰
                UIColor(red: 0.15, green: 0.08, blue: 0.18, alpha: 1.0).cgColor,   // 中紫灰
                UIColor(red: 0.18, green: 0.10, blue: 0.20, alpha: 1.0).cgColor,   // 浅紫灰
                UIColor(red: 0.20, green: 0.12, blue: 0.22, alpha: 1.0).cgColor,   // 紫灰色
                UIColor(red: 0.22, green: 0.14, blue: 0.25, alpha: 1.0).cgColor    // 淡紫灰
            ]
            
            // 创建渐变
            let colorSpace = CGColorSpaceCreateDeviceRGB()
            let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: nil)!
            
            // 绘制从左上到右下的渐变
            let startPoint = CGPoint(x: 0, y: 0)
            let endPoint = CGPoint(x: size.width, y: size.height)
            
            cgContext.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: [])
        }
    }
}

#Preview {
    ContentView()
}
